package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.rmi.RemoteException;
import java.util.Date;

import logic.Document;
import logic.Report;
import logic.Template;
import logic.TemplateEntry;

public class Reporter {

	public static Report report(String agent, String field, Date dateStart, Date dateEnd) throws RemoteException {
		String[] split = field.split(":");
		String templ = split[0];
		int id = Integer.valueOf(split[1]);
		Template template = new ServerRetriever<Template>(GlobalConfig.TEMPLATE).get(templ, "");
		TemplateEntry templateEntry = template.getById(id);

		Report rep = new Report();

		for (File dirs : new File("./data/" + GlobalConfig.DOCUMENT).listFiles()) {
			if (!agent.equals(dirs.getName()) && !"".equals(agent) && !"any".equals(agent))
				continue;
			for (File file : dirs.listFiles()) {
				long lastModified = file.lastModified();
				if ((dateEnd != null && lastModified > dateEnd.getTime())
						|| (dateStart != null && lastModified < dateStart.getTime()))
					continue;
				ObjectInputStream ois;
				try {
					ois = new ObjectInputStream(new FileInputStream(file));
					Document d = (Document) ois.readObject();
					ois.close();
					if (!templ.equals(d.getTemplateCode()))
						continue;
					rep.m.put(new Date(lastModified), d.getValue(templateEntry));


				} catch (Exception e) {
					e.printStackTrace();
					throw new RemoteException(null, e);
				}
			}
		}
		return rep;
	}

}
